//
//  SigninWorkViewController.swift
//  DSHCMerchant
//
//  Created by 罗德良 on 2018/5/4.
//  Copyright © 2018年 袋鼠好车. All rights reserved.
//

import UIKit
import Alamofire
import CoreLocation
class SigninWorkViewController: BaseViewController {
    
    @IBOutlet var goWorkBtn: UIButton!
    
    
    @IBOutlet var downWorkBtn: UIButton!
    
    @IBOutlet var userGoWorkTimeLabel: UILabel!
    
    @IBOutlet var userDownWorkTimeLabel: UILabel!
    
    @IBOutlet var weekDayLabel: UILabel!
    
    @IBOutlet var dateLabel: UILabel!
    
    @IBOutlet var goWorkTimeLabel: UILabel!
    
    @IBOutlet var downWorkTimeLabel: UILabel!
    
    //定位管理器
    let locationManager:CLLocationManager = CLLocationManager()
    var lat = ""
    var lon = ""
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        locationManager.stopUpdatingLocation()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        baseSetNavRightButtonWithTitle("历史打卡")
        weekDayLabel.text = NSDate.getWeekDay()
        dateLabel.text = NSDate.transformString(withFormat:"yyyy年MM月dd日", get: NSDate() as Date?)
        goWorkBtn.roundCorner(radius:5)
        downWorkBtn.roundCorner(radius:5)
        requestGetWorkTime()
        requestGetEmployeeWorkTime()
        creatLocationManager()
    }
    
    override func baseNavRightButtonPressed(_ button: UIButton) {
        
        let signinHistoryVC = SininWorkHistoryViewController()
        signinHistoryVC.title = "历史打卡"; self.navigationController?.pushViewController(signinHistoryVC, animated: true)
    }

    @IBAction func goWorkBtnPress(_ sender: UIButton) {
        if lat == "" || lon == "" {
            MBProgressHUD.alertShow(in: self.view, message: "尚未获取用户到用户的经纬度", hidenAfter: 0.8, mode: MBProgressHUDMode.text)
            return
        }
        requestGoWork(lat: lat, lon: lon)
    }
    
    
    @IBAction func downWorkBtnPress(_ sender: UIButton) {
        if lat == "" || lon == "" {
            MBProgressHUD.alertShow(in: self.view, message: "尚未获取用户到用户的经纬度", hidenAfter: 0.8, mode: MBProgressHUDMode.text)
            return
        }
        requestDownWork(lat: lat, lon: lon)
    }
    
    //获取员工自身打卡信息
    func requestGetEmployeeWorkTime() -> Void {
        Alamofire.request(getEmployeeWorkTimeUrl, method:.post, parameters:["sid":UserModel.shareUser.data?.storeId ?? String(),"uid":UserModel.shareUser.data?.uid ?? String()])
            .responseString { response in
                
                switch response.result.isSuccess {
                case true:
                    
                    var basemodel = BaseResponseOfModel<BaseArrayData<WorkTimeModel>>()
                    basemodel = BaseResponseOfModel.deserialize(from: response.value)!
                    
                    switch basemodel.status! {
                    case true:
                        if(basemodel.data?.data?.count)! > 0 {
                            let worktime = basemodel.data?.data![0]
                            if (worktime?.go_work_time != ""){
                                self.userGoWorkTimeLabel.text = "打卡时间" + (worktime?.go_work_time)!
                                    self.goWorkBtn.setTitle("已打卡", for: .normal)
                                
                                self.goWorkBtn.backgroundColor = UIColor.HexColor(0xa9a9a9)
                                
                                self.goWorkBtn.isEnabled = false
                            }
                            if (worktime?.closing_work_time != ""){
                                self.userDownWorkTimeLabel.text = "打卡时间" + (worktime?.closing_work_time)!
                                self.downWorkBtn.setTitle("已打卡", for: .normal)
                                self.downWorkBtn.backgroundColor = UIColor.HexColor(0xa9a9a9)
                            }
                            
                        }
                        print("获取成功")
                    case false:
                         MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                    }
                    
                case false:
                    print(response.result.error!)
                }
        }
    }
    
    
    //获取店铺上班时间
    func requestGetWorkTime() -> Void {
        Alamofire.request(getWorkTimeUrl, method:.post, parameters:["sid":UserModel.shareUser.data?.storeId ?? String(),"uid":UserModel.shareUser.data?.uid ?? String()])
            .responseString { response in
                
                switch response.result.isSuccess {
                case true:
                    
                    var basemodel = BaseResponseOfModel<BaseArrayData<WorkTimeModel>>()
                    basemodel = BaseResponseOfModel.deserialize(from: response.value)!
                    
                    switch basemodel.status! {
                    case true: 
                        if(basemodel.data?.data?.count)! > 0 {
                            let worktime = basemodel.data?.data![0]
                            self.goWorkTimeLabel.text = worktime?.go_work_time
                            self.downWorkTimeLabel.text = worktime?.closing_work_time
                        }else {
                            
                            MBProgressHUD.alertShow(in: self.view, message: "该店铺尚未设置上下班时间", hidenAfter: 1, mode: MBProgressHUDMode.text)
                            self.goWorkTimeLabel.text = "尚未设置"
                            self.downWorkTimeLabel.text = "尚未设置"
                            self.userGoWorkTimeLabel.isHidden = false
                            self.userGoWorkTimeLabel.isHidden = false
                            
                            self.goWorkBtn.isEnabled = false
                            self.downWorkBtn.isEnabled = false
                            
                        }
                        
                        
                        print("获取成功")
                    case false:
                         MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                    }
                    
                case false:
                    print(response.result.error!)
                }
        }
    }
    
    //上班打卡
    func requestGoWork(lat:String,lon:String) -> Void {
        
        let param =
            [
            "uid":UserModel.shareUser.data?.uid ?? String(),
             "sid":UserModel.shareUser.data?.storeId ?? String(),
             "latitude":lat,
             "longitude":lon,
             ] as [String : Any]
        Alamofire.request(goWorkUrl, method:.post, parameters:param)
            .responseString { response in
                
                switch response.result.isSuccess {
                case true:
                    
                    var basemodel = DefaultData()
                    basemodel = DefaultData.deserialize(from: response.value)!
                    
                    switch basemodel.status! {
                    case true:
                        self.requestGetEmployeeWorkTime()
                         MBProgressHUD.alertShow(in: self.view, message:"上班打卡成功", hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                    case false:
                         MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                    }
                    
                case false:
                    print(response.result.error!)
                }
                
        }
    }
    
    //下班打卡
    func requestDownWork(lat:String,lon:String) -> Void {
        
        let param =
            [
                "uid":UserModel.shareUser.data?.uid ?? String(),
                "sid":UserModel.shareUser.data?.storeId ?? String(),
                "latitude":lat,
                "longitude":lon,
                ] as [String : Any]
        Alamofire.request(downWorkUrl, method:.post, parameters:param)
            .responseString { response in
                
                switch response.result.isSuccess {
                case true:
                    
                    var basemodel = DefaultData()
                    basemodel = DefaultData.deserialize(from: response.value)!
                    
                    switch basemodel.status! {
                    case true:
                        self.requestGetEmployeeWorkTime()
                        MBProgressHUD.alertShow(in: self.view, message:"下班打卡成功", hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                        
                    case false:
                         MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                    }
                    
                case false:
                    print(response.result.error!)
                }
                
        }
    }
    
    func creatLocationManager() -> Void {
        //设置定位服务管理器代理
        locationManager.delegate = self as CLLocationManagerDelegate
        //设置定位进度
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        //更新距离
        locationManager.distanceFilter = 100
        ////发送授权申请
        locationManager.requestAlwaysAuthorization()
        if (CLLocationManager.locationServicesEnabled())
        {
            //允许使用定位服务的话，开启定位服务更新
            locationManager.startUpdatingLocation()
            print("定位开始")
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

extension SigninWorkViewController: CLLocationManagerDelegate{
    
    //定位改变执行，可以得到新位置、旧位置
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        //获取最新的坐标
        let currLocation:CLLocation = locations.last!
        self.lat = "\(currLocation.coordinate.latitude)"
        self.lon = "\(currLocation.coordinate.longitude)"
        
        //        label1.text = "经度：\(currLocation.coordinate.longitude)"
        //        //获取纬度
        //        label2.text = "纬度：\(currLocation.coordinate.latitude)"
        //        //获取海拔
        //        label3.text = "海拔：\(currLocation.altitude)"
        //        //获取水平精度
        //        label4.text = "水平精度：\(currLocation.horizontalAccuracy)"
        //        //获取垂直精度
        //        label5.text = "垂直精度：\(currLocation.verticalAccuracy)"
        //        //获取方向
        //        label6.text = "方向：\(currLocation.course)"
        //        //获取速度
        //        label7.text = "速度：\(currLocation.speed)"
    }
    
}
